package day4;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

//反射测试方法
public class TestMethod {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException,
            InvocationTargetException, IllegalAccessException {
        //1.获取类对象
        Class c = Class.forName("day4.Person");
        //2.获取方法
        Method[] ms = c.getDeclaredMethods();
        for (Method m:ms){
            //方法名
            String name = m.getName();
            //参数类型
            Class[] cs = m.getParameterTypes();
            Class result = m.getReturnType();
            System.out.println("方法:"+name+" 参数："+ Arrays.toString(cs)+" 返回:"+result);
        }
        //获取单个方法 然后进行调用
        //c.getDeclaredMethod(方法名,可变长的方法的参数)
        //test("a",131,true);
        Method m1 = c.getDeclaredMethod("test1");
        Method m2 = c.getDeclaredMethod("test2", String.class, Integer.class);
        Method m3 = c.getDeclaredMethod("test3", int.class, int.class);
        //开启私有权限
        m2.setAccessible(true);
        //调用方法 m1.invoke(对象,方法调用的实参)
        Person p = new Person(10);
        Object value = m1.invoke(p);
        Object value2 = m2.invoke(p,"chen",15);
        Object value3 = m3.invoke(p,4,7);
        System.out.println(value3);

    }
    //如果方法的参数 个数不确定(0-n个参数)
    //如果类型也不确定 可以定义Object
    //String ... a 表示可变长参数(本质上就是数组)
    public static void test(Object ... a){
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}
